package com.xtravel.common.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.*;
import com.xtravel.R;
import com.xtravel.common.constant.BrowserOpenType;
import com.xtravel.common.helper.ShareSdkHelper;

import java.util.ArrayList;

@SuppressLint("SetJavaScriptEnabled")
public class BrowserActivity extends FragmentActivity {
    private WebView browser;
    private FrameLayout shareFragmentLayout;
    private String url, title, content;
    private LinearLayout footerNavPanel;
    private ProgressBar pgrBar;
    private ImageButton backButton, forwardButton;
    private TextView txtShare;
    private Bundle argsData;
    private String opentype;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.browser_main_page);
        this.backButton = (ImageButton) findViewById(R.id.goback);
        this.forwardButton = (ImageButton) findViewById(R.id.goforward);
        backButton.setEnabled(false);
        forwardButton.setEnabled(false);
        this.browser = (WebView) findViewById(R.id.browser);
        this.txtShare = (TextView) findViewById(R.id.share);
        this.shareFragmentLayout = (FrameLayout) findViewById(R.id.shareFrameLayout);
        this.footerNavPanel = (LinearLayout) findViewById(R.id.footer_pannel);
        TextView txtTitle = (TextView) findViewById(R.id.textCaption);
        this.pgrBar = (ProgressBar) findViewById(R.id.myProgressBar);

        Intent intent = getIntent();
        argsData = intent.getExtras();
        this.url = intent.getStringExtra("url");
        this.title = intent.getStringExtra("title");
        this.content = intent.getStringExtra("content");
        this.opentype = intent.getStringExtra("opentype");
        txtTitle.setText(title);
        initBrowser(browser);
        this.initUIControls();
        browser.loadUrl(url);
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (browser.canGoBack()) {
                browser.goBack();
                return true;
            } else {
                onHotelBack();
                return true;
            }
        }

        return super.onKeyDown(keyCode, event);
    }

    private void initUIControls() {
        this.txtShare.setVisibility(View.GONE);
        switch (opentype) {
            case BrowserOpenType.Link:
                break;
            case BrowserOpenType.Link_Visa:
                this.footerNavPanel.setVisibility(View.GONE);
                break;
            case BrowserOpenType.Link_Hotel:
                //this.initShareFragment();
                break;
            case BrowserOpenType.Link_Hotel_Ad:
                this.txtShare.setVisibility(View.VISIBLE);
                this.footerNavPanel.setVisibility(View.GONE);
                break;
            case BrowserOpenType.Link_Share:
                this.txtShare.setVisibility(View.VISIBLE);
                break;
            default:
                break;
        }
    }

    @SuppressLint("NewApi")
    private void initBrowser(WebView browser) {
        browser.setWebViewClient(client);
        browser.setWebChromeClient(chromeClient);
        final WebSettings settings = browser.getSettings();
        settings.setSupportZoom(false);
        settings.setUseWideViewPort(true);
        settings.setJavaScriptEnabled(true);
        settings.setDomStorageEnabled(true);
        settings.setDatabaseEnabled(true);
        settings.setBuiltInZoomControls(false);
        settings.setDisplayZoomControls(false);
        //保险页面设置缩放比例
        if(this.url.contains("baoxian.html")) {
            //最小缩放等级
            browser.setInitialScale(25);
        }

        browser.requestFocusFromTouch();
    }

    public void onBack(View view) {
        if (BrowserOpenType.Link_Hotel.equals(opentype)) {
            onHotelBack();
        } else
            finish();
    }

    private void onHotelBack() {
        new AlertDialog.Builder(this)
                .setTitle("确认")
                .setMessage("您确定退出酒店搜索吗？")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                        finish();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                    }
                })
                .show();
    }

    public void onShare(View view) {
        ArrayList<String> urls = argsData.getStringArrayList("imgurl");
        String shareUrl = argsData.getString("shareurl");
        String shareTitle = argsData.getString("sharetitle");
        ShareSdkHelper.share(this, shareTitle, argsData.getString("content"), shareUrl, urls);
    }

    public void previousClick(View view) {
        browser.goBack();
    }

    public void nextClick(View view) {
        browser.goForward();
    }

    private WebViewClient client = new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            backButton.setEnabled(browser.canGoBack());
            forwardButton.setEnabled(browser.canGoForward());
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (BrowserOpenType.Link_Hotel.equals(opentype)) {
                getHotelBookingInfo(url);
            }

            view.loadUrl(url);
            return true;
        }
    };

    private WebChromeClient chromeClient = new WebChromeClient() {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            if (newProgress == 100) {
                pgrBar.setVisibility(View.INVISIBLE);
            } else {
                if (View.INVISIBLE == pgrBar.getVisibility()) {
                    pgrBar.setVisibility(View.VISIBLE);
                }
                pgrBar.setProgress(newProgress);
            }
            super.onProgressChanged(view, newProgress);
        }
    };

    private void initShareFragment() {
//        SearchHotelJumpFragment searchHotelJumpFragment = new SearchHotelJumpFragment(this.shareFragmentLayout);
//        searchHotelJumpFragment.setBackListner(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                shareFragmentLayout.setVisibility(View.GONE);
//                finish();
//            }
//        });

//        Fragment fragment = searchHotelJumpFragment;
//        FragmentManager fragmentManager = getSupportFragmentManager();
//        FragmentTransaction transaction = fragmentManager.beginTransaction();
//        transaction.replace(R.id.shareFrameLayout, fragment);
//        transaction.commit();
//        this.shareFragmentLayout.setVisibility(View.VISIBLE);
    }

    private void getHotelBookingInfo(String bookingUrl) {
//        if (!bookingUrl.startsWith("https://secure.booking.com/book.html?"))
//            return;
//
//        Pattern pattern = Pattern.compile(".*hotel_id=(\\d+?)&.*");
//        Matcher matcher = pattern.matcher(bookingUrl);
//        if (!matcher.find())
//            return;
//
//        final String hotelId = matcher.group(1);
//        new AsyncTask<Void, Void, Object>() {
//            @Override
//            protected Object doInBackground(Void... params) {
//                HotelRequest request = new HotelRequest();
//                return request.saveHotelScanInfo(hotelId);
//            }
//
//            @Override
//            protected void onPostExecute(Object data) {
//
//            }
//        }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    }
}
